#!/usr/lib/env python
# -*- encoding=utf-8 -*-

import os
import xlrd
import sys
import re
import requests
import base64
import json
import urllib

userName = "epdmintegration"
password = "epdmintegration"

class Config(object):
    def __init__(self):
       self.dir_path = os.path.abspath(os.path.dirname(__file__))
       self.conf_path = self.dir_path + '/binaryscan/conf/paramConfig.properties'
       self.xls_path = self.dir_path + '/binaryscan/EulerOS_V2R8C00-fossid-open_source.xls'
       self.sh_path = self.dir_path + '/binaryscan/startup.sh'
       self.excelReport_dir_path = self.dir_path + '/binaryscan/excelReport'


    def config_conf(self,path):
        #配置conf
        f = open(self.conf_path,'r+')
        data = ''
        for line in f.readlines():
           if (line.find('scanningPath=') == 0):
              line = 'scanningPath=' + path + '\n'
           elif (line.find('applylib=') == 0):
                line = 'applylib=' + self.xls_path + '\n'
           data += line
        f2 = open(self.conf_path,'w+')
        f2.write(data)
        f.close()
        f2.close()

        #将执行脚本中的路径改为绝对路径
        f3 = open(self.sh_path, 'r+')
        data = ''
        for line in f3.readlines():
           if (line.find('cd') == 0):
              line = 'cd ' + self.dir_path + '/binaryscan/tool' + '\n'
           elif (line.find('sh') == 0):
              line = 'sh ' + self.dir_path + '/binaryscan/tool/startupNoParam.sh' +'\n'
           data += line
        f4 = open(self.sh_path, 'w+')
        f4.write(data)
        f3.close()
        f4.close()


    def software_msg_querry(self,soft_params):
        url = 'http://pdm.huawei.com/Windchill/hwdispatcher/searchopensourceversioninfo/getVersionBySoftwareName'
        authorization = "Basic " + base64.b64encode(bytes(userName + ":" + password))
        params = soft_params
        #params = {"versionName": "Python", "versionNumber": "2.7.9", "queryType": "1"}
        headers = {
                'Authorization': authorization,
                'Content-type': 'application/x-www-form-urlencoded'
        }
        datas = ({'param': json.dumps(params)})
        try:
            r = requests.post(url, data=datas, headers=headers)
            software_info = json.loads(urllib.unquote(r.text))
            querry_status = software_info.get(u'isSuccess')
            querry_msg = software_info.get(u'msg')
            #print software_info
            #print querry_msg
            #print querry_status
            with open('querry_msg.txt','a') as msg:
                if querry_status != u'0' and querry_msg == u'find+null+by+software+name+and+version+':
                    message="{0}-{1} : find null by software name and version".format(params.get(u'versionName'),params.get(u'versionNumber'))
                    print message
                    msg.write(message + '\n')
                if querry_status == u'0':
                    software_msg = software_info.get(u'softVersionList')[0]
                    if software_msg.get(u'priority') == u'DXX':
                        print "{0}-{1} is DXX".format(params.get(u'versionName'), params.get(u'versionNumber'))
                        message = "{0}-{1} is DXX".format(params.get(u'versionName'), params.get(u'versionNumber'))
                        msg.write(message + '\n')
        except Exception as error:
            print error


        #如果脚本执行成功,就获取新报告,进行结果比对
    def confirm_result(self,result_sh):
        ret = 0
        if result_sh == 0:
            excelReport_open = os.popen('ls ./binaryscan/excelReport')
            excelReport_content = excelReport_open.read()
            l1 = excelReport_content.split('\n')
            new_excelReport_path = 'binaryscan/excelReport' + '/' + l1[-2]
            rb = xlrd.open_workbook(new_excelReport_path)
            table = rb.sheet_by_name('FileList0')
            pdm_version_number =table.row_values(0).index('PDM_Code Software Version')
            pdm_file_number =table.row_values(0).index('File')
            #print pdm_version_number
            nrows = table.nrows
            no_fedora29_list=[]
            for i in range(1, nrows):
                if table.row_values(i)[pdm_version_number] == "05833EGV Fedora Server 29" or table.row_values(i)[pdm_version_number] == "05833EGV Fedora 29":
                    continue
                else:
                    software = table.row_values(i)[pdm_file_number]
                    if re.search(r'((.tar.[\w]+)|(.zip)|(.patch)|(.tgz)|(.gem)|(.jar))',software):
                        print software
                        software_info=re.split(r'(([0-9]+[.|-]?)+)',re.split(r'([.][a-z]+)',software)[0])
                        print software_info
                        if len(software_info) > 1:
                            software_name=software_info[0][:-1]
                            software_version=software_info[1]
                            no_fedora29_list.append({"versionName": software_name, "versionNumber": software_version, "queryType": "1"})
                        else:
                            software_name=software_info[0]
                            software_version=""
                            with open('querry_msg.txt','a') as info:
                                message=message="{0} has no version".format(software)
                                info.write(message + '\n')
            if len(no_fedora29_list) > 0:
                print no_fedora29_list
                for i in no_fedora29_list :
                    self.software_msg_querry(i)
                if os.path.exists(self.dir_path+'/querry_msg.txt'):
                    ret = 1
                else:
                    ret = 0
            else:
                ret =0 
        return ret

if __name__ == '__main__':
    config = Config()
    scanningPath = sys.argv[1]
    config.config_conf(scanningPath)
    txt=open("data.txt",'w+')
    txt.write(scanningPath+'\n')
    txt.close()
    result_sh = os.system(config.sh_path)
    ret = config.confirm_result(result_sh)
    if ret != 0:
        os.system('echo \"fail\" > result')
    else:
        os.system('echo \"success\" > result')
  
     
